package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.template.AipFaceTemplate;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.commons.template.OssTemplate;
import com.tanhua.commons.template.SmsTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.CommonLikeUser;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {
    @Reference
    private UserApi userApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private SettingsApi settingsApi;
    @Reference
    private BlackListApi blackListApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    private String tokenPrefix = "TOKEN_";


    public ResponseEntity findUserInfo(Long id) {
        //1. 查询id对应的用户信息UserInfo
        UserInfo userInfo = userInfoApi.findById(id);
        //2. 把结果转换成APP需要的数据UserInfoVO
        UserInfoVO vo = new UserInfoVO();
        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo.getAge() != null) {
            vo.setAge(String.valueOf(userInfo.getAge()));
        }
        //3. 返回结果
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity updateUserInfo(UserInfo userInfo) {
        //获取当前用户
        User user = UserHolder.getUser();
        //把user的id设置到userInfo对象
        userInfo.setId(user.getId());
        //userInfo更新到数据库
        userInfoApi.update(userInfo);
        //返回
        return ResponseEntity.ok(null);
    }

    public ResponseEntity updateHeadPhoto(MultipartFile headPhoto) throws IOException {
        //获取当前用户
        User user = UserHolder.getUser();
        //人脸检测
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!detect) {
            return ResponseEntity.status(500).body(ErrorResult.faceDetectFailed());
        }
        //图片上传到阿里云
        String path = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        // 更新到数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar(path);
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity findSettings() {
        //获取当前用户
        User user = UserHolder.getUser();
        //查询陌生人的问题
        Question question = questionApi.findByUserId(user.getId());
        //查询通知设置
        Settings settings = settingsApi.findByUserId(user.getId());
        //构造返回值
        SettingsVO vo = new SettingsVO();
        //封装联系人问题
        if (question != null) {
            vo.setStrangerQuestion(question.getTxt());
        }
        //封装通知设置
        if (settings != null) {
            //如果查询到了通知设置，加载这些设置
            BeanUtils.copyProperties(settings, vo);
        } else {
            vo.setGonggaoNotification(true);
            vo.setLikeNotification(true);
            vo.setPinglunNotification(true);
        }
        //设置手机号
        vo.setPhone(user.getMobile());
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findBlackList(int page, int pagesize) {
        //获取当前用户
        User user = UserHolder.getUser();
        //查询当前用户的黑名单列表
        IPage<UserInfo> iPage = blackListApi.findByUserId(page, pagesize, user.getId());
        //构造返回值
        PageResult<UserInfo> vo = new PageResult<>();
        vo.setCounts((int) iPage.getTotal());
        vo.setPage(page);
        vo.setPages((int) iPage.getPages());
        vo.setPagesize(pagesize);
        vo.setItems(iPage.getRecords());
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity removeBlackList(Long blackUserId) {
        //获取当前用户的id
        Long userId = UserHolder.getUserId();
        //移出黑名单
        blackListApi.delete(userId, blackUserId);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity updateQuestion(String questionTxt) {
        //获取当前用户
        User user = UserHolder.getUser();
        //查询当前用户的陌生人问题
        Question question = questionApi.findByUserId(user.getId());
        //设置陌生人问题
        if (question != null) {
            //如果用户设置过陌生人问题，就修改
            question.setTxt(questionTxt);
            questionApi.update(question);
        } else {
            //当前用户没有设置过陌生人问题，新增
            question = new Question();
            question.setUserId(user.getId());
            question.setTxt(questionTxt);
            questionApi.save(question);
        }
        return ResponseEntity.ok(null);
    }

    public ResponseEntity saveSettings(Settings settings) {
        //获取当前用户的id
        Long userId = UserHolder.getUserId();
        //查询当前用户的通知设置
        Settings userSettings = settingsApi.findByUserId(userId);
        if (userSettings == null) {
            //没有查询到通知设置，新增
            settings.setUserId(userId);
            settingsApi.save(settings);
        } else {
            //查询到通知设置，修改
            settings.setId(userSettings.getId());
            settingsApi.update(settings);
        }
        return ResponseEntity.ok(null);
    }

    public ResponseEntity sendVerificationCode() {
        //获取当前用户
        User user = UserHolder.getUser();
        //发送短信验证码
        //String code = smsTemplate.sendSms(user.getMobile());
        String code = "123456";
        //验证码保存到redis,5分钟内有效
        redisTemplate.opsForValue().set("CODE_" + user.getMobile(), code, Duration.ofMinutes(5));

        return ResponseEntity.ok(null);
    }

    public ResponseEntity checkVerificationCode(String code) {
        //获取当前用户
        User user = UserHolder.getUser();
        //从redis中获取验证码，对比
        String redisCode = redisTemplate.opsForValue().get("CODE_" + user.getMobile());
        if (code == null || !code.equals(redisCode)) {
            return ResponseEntity.status(500).body(ErrorResult.smsInvalid());
        }
        //验证正确，删除redis中的验证码
        redisTemplate.delete("CODE_" + user.getMobile());
        //构造返回值
        Map<String, Object> map = new HashMap<>();
        map.put("verification", true);
        return ResponseEntity.ok(map);
    }

    public ResponseEntity updateMobile(String newPhone) {
        //获取当前用户
        User user = UserHolder.getUser();
        //跟新手机号
        user.setMobile(newPhone);
        userApi.update(user);
        UserHolder.setUser(user);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity findCounts() {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //获取喜欢数
        long likeCount = userLikeApi.queryLikeCount(userId);
        //获取粉丝数
        long fansCount = userLikeApi.queryFansCount(userId);
        //获取好友数
        long friendsCount = userLikeApi.queryFriendsCount(userId);

        //构造返回值
        Map<String, Object> map = new HashMap<>();
        map.put("eachLoveCount", friendsCount);
        map.put("loveCount", likeCount);
        map.put("fanCount", fansCount);
        return ResponseEntity.ok(map);
    }

    public ResponseEntity userLikeList(Integer type, int page, int pagesize) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();

        PageResult<CommonLikeUser> pageResult = null;
        if (type == 1) {
            //1 互相关注
            pageResult = userLikeApi.queryFriendsList(userId, page, pagesize);
        } else if (type == 2) {
            //2 我关注
            pageResult = userLikeApi.queryLikeList(userId, page, pagesize);
        } else if ((type == 3)) {
            //3 粉丝
            pageResult = userLikeApi.queryFansList(userId, page, pagesize);
        } else if (type == 4) {
            //4 谁看过我
            pageResult = userLikeApi.findVisitorList(userId, page, pagesize);
        }

        List<CommonLikeUserVO> voList = new ArrayList<>();
        for (CommonLikeUser commonLikeUser : pageResult.getItems()) {
            CommonLikeUserVO vo = new CommonLikeUserVO();

            UserInfo userInfo = userInfoApi.findById(commonLikeUser.getTargetUserId());
            BeanUtils.copyProperties(userInfo,vo);
            vo.setMatchRate(commonLikeUser.getScore().intValue());
            vo.setAlreadyLove(false);
            voList.add(vo);
        }
        PageResult<CommonLikeUserVO> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);
        return ResponseEntity.ok(voPageResult);
    }

    public ResponseEntity likeFans(Long fansId) {
        //从粉丝列表删除
        userLikeApi.delete(fansId, UserHolder.getUserId());
        //把好友关系记录到好友表
        friendApi.addFriend(fansId, UserHolder.getUserId());
        //在环信注册好友信息
        huanXinTemplate.addContactUser(fansId, UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }

    public ResponseEntity deleteLike(Long uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        Friend friend=friendApi.findById(userId, uid);
        if (friend != null) {
            friendApi.delete(userId, uid);
            UserLike userLike = new UserLike();
            userLike.setId(ObjectId.get());
            userLike.setUserId(uid);
            userLike.setLikeUserId(userId);
            userLike.setCreated(System.currentTimeMillis());
            userLikeApi.save(userLike);
        } else {
            userLikeApi.delete(userId,uid);
        }
        return ResponseEntity.ok(null);
    }
}
